from django.dispatch.dispatcher import logger
from rest_framework.permissions import AllowAny, IsAuthenticated
from user.models import User, Clazz
from task.models import TaskUser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db import IntegrityError
from django.contrib.auth import get_user_model


class RegisterView(APIView):

    permission_classes = [AllowAny,]
    def post(self, request):
        data = request.data
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        name = data.get('name')
        clazz_id = data.get('clazz_id')

        if not username or not password or not email or not name or not clazz_id:
            return Response({'message': '信息填写不完整'}, status=status.HTTP_400_BAD_REQUEST)

        if User.objects.filter(username=username).exists():
            return Response({'message': '用户名已存在'}, status=status.HTTP_400_BAD_REQUEST)
        if User.objects.filter(email=email).exists():
            return Response({'message': '邮箱已存在'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            User.objects.create_user(username=username, password=password, email=email, name=name, clazz_id=clazz_id)
            # 如需保存tel、clazz、role等扩展信息，请用Profile模型或自定义User
            return Response({'message': '注册成功'}, status=status.HTTP_200_OK)
        except IntegrityError:
            return Response({'message': '注册失败，数据库错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ClazzView(APIView):
    permission_classes = [AllowAny, ]

    def get(self, request):

        try:
            queryset = Clazz.objects.filter(is_delete=0)
            data = [{
                'id': clazz.id,
                'name': clazz.name,
                'duration': clazz.duration,
                'manage_name': clazz.manage_name
            } for clazz in queryset]

            return Response({'classes': data}, status=status.HTTP_200_OK)

        except Clazz.DoesNotExist:
            return Response({'message': '班级不存在'}, status=status.HTTP_404_NOT_FOUND)

        except Exception as e:
            logger.error(f"获取班级信息失败: {str(e)}")
            return Response({'message': '获取班级信息失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class PasswordResetView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request, *args, **kwargs):
        old_password = request.data.get('oldPassword')
        new_password = request.data.get('password')
        new_password2 = request.data.get('password2')

        # 获取真实的数据库用户对象
        User = get_user_model()
        try:
            user = User.objects.get(id=request.user.id)
        except User.DoesNotExist:
            return Response(
                {"detail": "用户不存在或已被删除。"},
                status=status.HTTP_404_NOT_FOUND
            )

        # 1. 检查所有密码字段是否提供
        if not old_password or not new_password or not new_password2:
            return Response(
                {"detail": "请填写所有密码字段。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 验证新密码和确认密码是否一致
        if new_password != new_password2:
            return Response(
                {"detail": "两次输入的新密码不一致。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 验证原密码是否正确
        if not user.check_password(old_password):
            return Response(
                {"detail": "原密码不正确。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 4. 密码不能与旧密码相同
        if user.check_password(new_password):
            return Response(
                {"detail": "新密码不能与原密码相同。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 5. 更新密码
        user.set_password(new_password)
        user.save()

        return Response(
            {"detail": "密码修改成功！"},
            status=status.HTTP_200_OK
        )


        

class Reset(APIView):
    """重置用户密码为123456"""
    permission_classes = [AllowAny]

    def get(self, request):
        try:
            # 获取用户ID
            user_id = request.query_params.get('user_id') or request.GET.get('user_id') or request.data.get('user_id')
            
            if not user_id:
                return Response({"message": "缺少必要参数user_id"}, status=status.HTTP_400_BAD_REQUEST)
            
            try:
                # 查找用户
                user = User.objects.get(id=user_id)
                
                # 重置密码为123456
                user.set_password('123456')
                user.save()
                
                return Response({"message": f"用户 {user.username} 的密码已重置为123456"}, status=status.HTTP_200_OK)
                
            except User.DoesNotExist:
                return Response({"message": "未找到对应的用户"}, status=status.HTTP_404_NOT_FOUND)
                
        except Exception as e:
            return Response({"message": f"重置密码失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class DisableUser(APIView):
    """禁用用户，将is_active改为flase/0"""
    permission_classes = [AllowAny]

    def get(self,request):
        try:
            # 获取用户ID
            user_id = request.query_params.get('user_id') or request.GET.get('user_id') or request.data.get('user_id')
            
            if not user_id:
                return Response({"message": "缺少必要参数user_id"}, status=status.HTTP_400_BAD_REQUEST)
            
            try:
                # 查找用户
                user = User.objects.get(id=user_id)
                
                # 禁用用户
                user.is_active = False
                user.save()
                
                return Response({"message": f"用户 {user.username} 已禁用"}, status=status.HTTP_200_OK)
                
            except User.DoesNotExist:
                return Response({"message": "未找到对应的用户"}, status=status.HTTP_404_NOT_FOUND)
                
        except Exception as e:
            return Response({"message": f"禁用失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)